package com.heima.wemedia.service.impl;

import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.statistic.dtos.StatisticsDto;
import com.heima.model.statistic.pojos.WmNewsStatistics;
import com.heima.model.statistic.vos.ChartDataVo;
import com.heima.model.statistic.vos.FansVO;
import com.heima.model.statistic.vos.StatisticsVo;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.service.WmNewsStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class WmNewsStatisticsServiceImpl implements WmNewsStatisticsService {

    @Autowired
    MongoTemplate mongoTemplate;

    //数据统计
    @Override
    public ResponseResult watchStatistics(StatisticsDto dto) {
        Map<String, Object> map = new HashMap<>();
        //参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数错误");
        }
        //判断type  0 今日，1 本周，7 近七天，30 近三十天
        WmUser wmUser = WmThreadLocalUtils.getUser();

        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "需要登陆");
        }
        Integer userId = wmUser.getId();
        //格式化时间
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = new Date();
        String str1 = sdf1.format(d1);
        // 方法抽取
        Map<String, Object> result = getDataByType(dto, userId);
        return ResponseResult.okResult(result);


    }

    //粉丝概况
    @Override
    public ResponseResult fansListHand(StatisticsDto dto) {
        //参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数错误");
        }
        //判断用户登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "需要登陆");
        }
        Integer userId = wmUser.getId();

        List<FansVO> resultFans = new ArrayList<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String minDate = sdf.format(new Date(Long.parseLong(String.valueOf(dto.getStime()))));

        Query query = Query.query(Criteria.where("userId").is(userId).and("creatTime").gte(minDate));

        List<WmNewsStatistics> wmNewsStatisticsList = mongoTemplate.find(query, WmNewsStatistics.class);
        if (wmNewsStatisticsList == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在");
        }
        for (WmNewsStatistics statistics : wmNewsStatisticsList) {
            FansVO fansVO = new FansVO();
            fansVO.setArticle(statistics.getArticleCount());
            fansVO.setCollection(statistics.getCollect());
            fansVO.setComment(statistics.getComment());
            fansVO.setCreated_time(statistics.getCreatTime());
            fansVO.setRead_count(statistics.getReadCount());
            fansVO.setLikes(statistics.getLikes());
            fansVO.setUnlikes(statistics.getUnLikes());
            resultFans.add(fansVO);
        }
        if (CollectionUtils.isNotEmpty(resultFans)) {
            return ResponseResult.okResult(resultFans);
        }
        return null;
    }


    //封装返回结果
    private Map<String, Object> getDataByType(StatisticsDto dto, Integer userId) {
        Map<String, Object> map = new HashMap<>();
        Long eTime = dto.getEtime();
        Long sTime = dto.getStime();
        //格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String maxDate = sdf.format(new Date(Long.parseLong(String.valueOf(eTime))));      // 时间戳转换成时间
        String minDate = sdf.format(new Date(Long.parseLong(String.valueOf(sTime))));      // 时间戳转换成时间
        log.info("起始{}", minDate);
        log.info("结束{}", maxDate);
        Query query = Query.query(Criteria.where("userId").is(userId).and("creatTime").gte(minDate));
        List<WmNewsStatistics> wmNewsStatisticsList = mongoTemplate.find(query, WmNewsStatistics.class);
        if (wmNewsStatisticsList == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在");
        }
        Long articleNum = 0l;
        Long readCount = 0l;
        Long fanReadNum = 0l;
        Long comment = 0l;
        Long collect = 0l;
        String creatTime = null;
        ArrayList<StatisticsVo> list = new ArrayList<>();
        for (WmNewsStatistics wmNewsStatistics : wmNewsStatisticsList) {
            articleNum += wmNewsStatistics.getArticleCount();
            readCount += wmNewsStatistics.getReadCount();
            fanReadNum += wmNewsStatistics.getFanReadNum();
            comment += wmNewsStatistics.getComment();
            collect += wmNewsStatistics.getCollect();
            creatTime = wmNewsStatistics.getCreatTime();
            StatisticsVo statisticsVos = new StatisticsVo();

            StatisticsVo statisticsVo = wmNewsStatisticsToStatisticsVo(wmNewsStatistics, statisticsVos);
            list.add(statisticsVo);


        }


        //构造StatisticsVo
        StatisticsVo statisticsVo = new StatisticsVo();
        statisticsVo.setArticleNum(articleNum);
        statisticsVo.setReadNum(readCount);
        statisticsVo.setFanReadNum(fanReadNum);
        statisticsVo.setCommentNum(comment);
        statisticsVo.setFavNum(collect);
        statisticsVo.setDate(creatTime);


        map.put("topItems", statisticsVo);
        map.put("tableData", list);
        //封装饼状图
        Map<String, List> map2 = new HashMap<>();
        ArrayList<Object> dataList = new ArrayList<>();
        List<String> chineseList = new ArrayList<>();
        Collections.addAll(chineseList, "文章量", "阅读量", "粉丝阅读", "评论量");
        ArrayList<Long> valuesList = new ArrayList<>();
        Collections.addAll(valuesList, articleNum, readCount, fanReadNum, comment);

        for (int i = 0; i < chineseList.size(); i++) {
            ChartDataVo chartDataVo = new ChartDataVo();
            chartDataVo.setName(chineseList.get(i));
            chartDataVo.setValue(valuesList.get(i));
            dataList.add(chartDataVo);
        }
        map2.put("data", dataList);
        map.put("chartData", map2);
        return map;
    }

    //封装StatisticsVo
    private StatisticsVo wmNewsStatisticsToStatisticsVo(WmNewsStatistics wmNewsStatistics, StatisticsVo statisticsVo) {
        statisticsVo.setArticleNum(wmNewsStatistics.getArticleCount());
        statisticsVo.setReadNum(wmNewsStatistics.getFanReadNum());
        statisticsVo.setFanReadNum(wmNewsStatistics.getFanReadNum());
        statisticsVo.setCommentNum(wmNewsStatistics.getComment());
        statisticsVo.setFavNum(wmNewsStatistics.getCollect());
        statisticsVo.setDate(wmNewsStatistics.getCreatTime());
        return statisticsVo;
    }
}
